<template>
  <view class="content">
    <view class="swiper">

  <!-- 循环显示每张图片，最多显示 3 张 -->
	<swiper 
	  class="swiper" 
	  indicator-dots="true" 
	  autoplay="false" 
	  indicator-color="#00aa00"
	>
	  <swiper-item
	    v-for="(image, index) in (productDetail.images.length > 3 ? productDetail.images.slice(0, 3) : productDetail.images)"
	    :key="index"
	    class="swiper-item"
	    :style="{ 
	      backgroundImage: `url(${image.imageUrl})`, 
	
	    }"
	  >
	  </swiper-item>
	</swiper>


    </view>
    
    <!-- 显示商品名称、价格、库存等详情 -->
    <view class="product-info">
      <view class="product-price">￥{{ productDetail.price }}/{{ productDetail.unit }}</view>
      <view class="product-name">{{ productDetail.productName }}</view>
      <view class="product-description">{{ productDetail.description }}</view>
	  <view class="div"></view>
      <view class="icon-group">
       <uni-icons type="star"size="15" color="#ff9900" >收藏</uni-icons>
        <uni-icons type="redo" size="15" color="#ff9900">分享</uni-icons>
      </view>
    </view>

    <!-- 显示商品属性 -->
    <view class="product-property">
      <uni-row class="property-row" >
        <uni-col :span="6">
          <text class="property-info">发货地</text>
        </uni-col>
        <uni-col :span="18">
          <text class="property-value">{{ productDetail.originLocation }}</text>
        </uni-col>
      </uni-row>

   <view class="clickable-property" @click="showPopup">
     <uni-row class="property-row">
       <uni-col :span="6" class="property-item">
         <view class="property-info">属性</view>
       </uni-col>
   
       <uni-col :span="5" class="property-item">
         <view class="property-value">{{ productDetail.productType }}</view>
         <view class="property-label">类型</view>
       </uni-col>
   
       <uni-col :span="5" class="property-item">
         <view class="property-value">{{ productDetail.grade }}</view>
         <view class="property-label">等级</view>
       </uni-col>
   
       <uni-col :span="5" class="property-item">
         <view class="property-value">{{ productDetail.size }}</view>
         <view class="property-label">大小</view>
       </uni-col>
   
       <uni-col :span="3" class="property-item">
         <uni-icons type="right" size="30" class="arrow-icon"></uni-icons> <!-- 右箭头图标 -->
       </uni-col>
     </uni-row>
   </view>
	  
	<uni-row class="info-row">
        <uni-col :span="24">
          <text class="property-info">正品保障 | 包邮 | 假一赔十</text>
        </uni-col>
      </uni-row>
   
    <!-- 底部属性弹窗 -->
    <uni-popup ref="propertyPopup" type="bottom" :mask-click="true">
      <view class="popup-content">
        <view class="popup-header" >商品属性</view>
        
        <uni-row>
			<view class="popup-property-row">
          <uni-col :span="8"  ><view class="popup-property-label">产品类型</view></uni-col>
          <uni-col :span="16" ><view class="popup-property-value">{{ productDetail.productType }}</view></uni-col>
          </view>
		</uni-row>
		
        <view class="divider2"></view>
    
        <uni-row>
			<view class="popup-property-row">
          <uni-col :span="8" ><view class="popup-property-label">货品等级</view></uni-col>
          <uni-col :span="16"><view class="popup-property-value">{{ productDetail.grade }}</view></uni-col>
          </view>
		</uni-row>
		
        <view class="divider2"></view>
    
        <uni-row >
			<view class="popup-property-row">
          <uni-col :span="8"><view class="popup-property-label">产品大小</view></uni-col>
          <uni-col :span="16" ><view class="popup-property-value">{{ productDetail.size }}</view></uni-col>
		  </view>
		</uni-row>
		
        <view class="divider2"></view>
    
        <uni-row >
			<view class="popup-property-row">
          <uni-col :span="8"><view class="popup-property-label">单份重量</view></uni-col>
          <uni-col :span="16"><view class="popup-property-value">{{ productDetail.unitWeight }}</view></uni-col>
         </view>
		</uni-row>
      </view>
    </uni-popup>
    </view>
	    <!-- 店铺信息 -->
	    <view class="shop-info"  >
	        <view class="info-row1">
	            <image :src="shopInfo.shopLogo" class="shop-logo" alt="店铺Logo" />
	            <view class="shop-header">
	                <text class="shop-name">{{ shopInfo.shopName }}</text>
					<button class="follow-btn" @click="goToShop">进店看看<uni-icons type="right" size="20"></uni-icons></button>
	            </view>
	        </view>
			
	        <!-- 介绍和其他信息的分行布局 -->
	        <view class="shop-details">
	            <text class="description">{{ shopInfo.shopDescription }}</text>
	            <view class="info-row2">
	                <text class="shop-rating">评分：{{ shopInfo.shopRating }}</text>
	
	                 <!-- 使用星星图标表示等级 -->
					 <view class="shop-level">等级：
	                          <view  v-for="i in shopInfo.shopLevel" :key="i">
	                            <uni-icons class="icons" type="star-filled" size="15" color="#ff9900"></uni-icons></view>
	                          </view>
							
	                <text class="shop-status">
	                    状态：{{ shopInfo.shopStatus === '0' ? '营业中' : '暂停营业' }}
	                </text>
	            </view>
	        </view>
	    </view>
		<!--商品图片-->
		<scroll-view class="image_scroll">
		  <view class="icon-text-container">
			<uni-icons type="arrow-down" size="20" color="#5e5e5e"></uni-icons>
			<text class="text">商品详情</text>
		  </view>
		  <view v-for="(item, index) in productDetail.images" :key="index" class="image_wrapper">
			<image 
			  class="image_item" 
			  :src="item.imageUrl" 
			  mode="widthFix" 
			  lazy-load
			></image>
		  </view>
		  <view class="introduce">
			<introduce></introduce>
		  </view>
		</scroll-view>

	
		<!-- 底部导购 -->
		<view class="footer">
		  <!-- 分享 -->
		  <view class="footer-item" >
		    <uni-icons type="redo-filled" size="20" color="#00aa00"></uni-icons>
		    <text>分享</text>
		  </view>
		  
		  <!-- 联系客服 -->
		  <view class="footer-item">
		    <uni-icons type="phone-filled" size="20" color="#ff0000" @click="conect"></uni-icons>
		    <text>联系客服</text>
		  </view>
		  
		  <!-- 加入购物车 -->
		  <view class="footer-item add-to-cart" @click="showStuPopupCart()">
		    <uni-icons type="cart" size="20" color="#f1f100"></uni-icons>
		    <text>加入购物车</text>
		  </view>
		  
		  <!-- 立即购买 -->
		  <view class="footer-item buy-now" @click="showStuPopup()">
		    <text>立即购买</text>
		  </view>
		</view>
		

	<!-- 商品规格弹窗 -->
	<uni-popup ref="stuPopup" type="bottom" :safe-area="true">
	  <view class="popup-content">
	    <view class="popup-header">
	      <text>{{productDetail.productName}}</text>
	    </view>
	    <view class="popup-body">
	      <!-- 商品规格 -->
	      <view v-for="(sku, index) in skuList" :key="index" class="sku-item">
	        <view class="sku-name">{{ sku.skuName }}</view>
			  <text class="sku-price">￥{{sku.price}}/{{sku.unit}}</text>
	        <view class="sku-quantity">
	          <!-- 规格数量操作 -->
	          <button class="decrement-btn" @click="decrementQuantity(index)">-</button>
	          <input class="quantity-input" type="number" v-model="sku.quantity" @input="validateQuantity(index)" />
	          <button class="increment-btn" @click="incrementQuantity(index)">+</button>
	        </view>
	      </view>
	    </view>
	    <view class="popup-footer">
	      <!-- 显示合计金额 -->
	      <view class="total-amount">合计：￥{{ calculateTotal() }}</view>
	      <button class="confirm-btn" @click="confirmSku" v-if="buy">确定支付</button>
		<button class="confirm-btn" @click="inCart" v-if="!buy">确定加入</button>
	    </view>
	  </view>
	</uni-popup>

  </view>
</template>

<script>
import { getProductDetail, getSku } from '../../../api/productDetail/productDetail';
import { getShopDetail} from '../../../api/shop/index.js';
import { addCart } from '../../../api/cart/cart';
export default {
  data() {
    return {
      productId: null, // 商品ID
      productDetail: {images: [], // 确保 images 初始值为数组
	  }, // 存储商品详情
      shopInfo: {}, // 店铺信息
      skuList: [], // 商品规格
	  buy:false,
	  userId:null,
    };
  },
  onLoad(options) {
	  
	  if (!this.userId) {
	    this.$store
	      .dispatch('GetInfo')
	      .then(() => {
	        this.userId = this.$store.state.user.userId;
	        console.log("用户ID:", this.userId);
	      })
	      .catch((error) => {
	        console.error("获取用户信息失败:", error);
	      });
	  }

	
    // 获取传入的商品ID
    this.productId = options.productID;
    this.fetchProductDetail(this.productId);
  },
  methods: {
    async fetchProductDetail(productId) {
      try {
        const data = await getProductDetail(productId);
        this.productDetail = data;
        this.getShopInfo();
      } catch (error) {
        console.error('商品加载失败！', error);
      }
    },
    async getShopInfo() {
      try {
        const data = await getShopDetail(this.productDetail.userId);
        this.shopInfo = data;
      } catch (error) {
        console.error('获取店铺信息失败:', error);
      }
    },
    async getSkuList() {
      try {
        const data = await getSku(this.productId);
        // 为每个 SKU 动态添加初始的 `quantity` 属性
        this.skuList = data.map((sku) => ({
          ...sku,
          quantity: 0, // 默认设置为最小购买量
        }));
      } catch (error) {
        console.error('获取规格信息失败:', error);
      }
    },
	
	
	async inCart()
	{
		// 筛选出已选择的 SKU（数量大于 0）
		  const selectedSkus = this.skuList.filter((sku) => sku.quantity > 0);
		
		  if (selectedSkus.length === 0) {
		    this.$refs.stuPopup.close();
		    return;
		  }
		
		  // 转换数据为 JSON 字符串
		//const orderData = JSON.stringify(selectedSkus);
		 try{
		 	 await addCart(selectedSkus,this.userId)
			 uni.showToast({
			     title: '已加入',
			     icon: 'success',
			     duration: 1000 // 持续时间，单位为毫秒
			 });
		 }catch(e){
		 	//TODO handle the exception
			uni.showToast({
			    title: '操作失败',
			    icon: 'fail',
			    duration: 2000 // 持续时间，单位为毫秒
			});
		 }
		 
		  
		  
		  //console.log(orderData)
		  //const productListData = JSON.stringify(this.productDetail.productId); // 添加 productList 的值
		
		  // 跳转到确认订单页面，传递数据，包括 userId 和 productList
		  // wx.navigateTo({
		  //   url: `/pages/product/confirm/confirm?orderData=${encodeURIComponent(orderData)}&productList=${encodeURIComponent(productListData)}`,
		  // });
		  // this.$refs.stuPopup.close();
		
	},
	
	
	showPopup() {
	      this.$refs.propertyPopup.open();
		  
	    },
		showStuPopupCart(){
			this.getSkuList();
			this.$refs.stuPopup.open();
			this.buy=false;
		},
	goToShop()
	{ 
		wx.navigateTo({ url: `/pages/shop/index/index?userId=${this.productDetail.userId}`, }); 
	}, 
    showStuPopup() {
      this.getSkuList();
      this.$refs.stuPopup.open();
	  this.buy=true;
    },
    // 减少数量
    decrementQuantity(index) {
      const sku = this.skuList[index];
      if (sku.quantity > 0) {
        sku.quantity--;
      }
    },
    // 增加数量
    incrementQuantity(index) {
      const sku = this.skuList[index];
      if (!sku.maxPurchase || sku.quantity < sku.maxPurchase) {
        sku.quantity++;
      } else {
        wx.showToast({
          title: `最多只能购买 ${sku.maxPurchase} 件`,
          icon: 'none',
        });
      }
    },
	conect(){
		 uni.makePhoneCall({ phoneNumber: '17807745341' });
	},
    // 校验输入的数量
    validateQuantity(index) {
      const sku = this.skuList[index];
      if (sku.quantity < sku.minPurchase&&sku.quantity>0) {
        wx.showToast({
          title: `最低购买量为 ${sku.minPurchase}`,
          icon: 'none',
        });
        sku.quantity = sku.minPurchase;
      } else if (sku.maxPurchase && sku.quantity > sku.maxPurchase) {
        wx.showToast({
          title: `最多只能购买 ${sku.maxPurchase} 件`,
          icon: 'none',
        });
        sku.quantity = sku.maxPurchase;
      }
    },
    // 计算合计金额
    calculateTotal() {
      return this.skuList
        .reduce((total, sku) => total + sku.price * sku.quantity, 0)
        .toFixed(2); // 保留两位小数
    },
    // 确认选择的规格
    confirmSku() {
      // 筛选出已选择的 SKU（数量大于 0）
      const selectedSkus = this.skuList.filter((sku) => sku.quantity > 0);
    
      if (selectedSkus.length === 0) {
        this.$refs.stuPopup.close();
        return;
      }
    
      // 转换数据为 JSON 字符串
      const orderData = JSON.stringify(selectedSkus);
      const productListData = JSON.stringify(this.productDetail); // 添加 productList 的值
    
      // 跳转到确认订单页面，传递数据，包括 userId 和 productList
      wx.navigateTo({
        url: `/pages/product/confirm/confirm?orderData=${encodeURIComponent(orderData)}&productList=${encodeURIComponent(productListData)}`,
      });
      this.$refs.stuPopup.close();
    }
  },
};
</script>


<style lang="scss">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
}

.swiper {
  width: 100%;
  height: 240px; /* 设置轮播图的高度 */
}

.swiper-item {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.product-info {
  width: 100%;
  padding: 10px;
  border-radius: 10px;
  background-color: #fcfcfc;
  margin-top: 10px;
}

.product-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-price {
  color: #ff0000;
  font-size: 25px;
}

.icon-group {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.product-property {
  width: 100%;
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
}

.property-info{
	margin-left: 10rpx;
	font-size: 20px;
	font-weight: bold;
}


.property-label {
  font-size: 15px;
  color: #999;
}

.property-value {
  font-size: 15px;
}

.info-row {
  margin-top: 10px;
  
}

.info-text {
  font-size: 20px;
}

.clickable-property {
  padding: 10px;
  cursor: pointer;
}
.property-row {
  display: flex;

}
.property-item {
  
}

.arrow-icon {
  display: flex;
  justify-content: flex-end;
}

.property-title {
  font-size: 20px;
  font-weight: bold;
}

.property-value {
  font-size: 18px;
  font-weight: bold;
}

.div{
	width: 100%;
	height: 1px;
	background-color: #ccc;
	margin: 7px 5px;
}

.divider {
  width: 1px;
  height: 24px;
  background-color: #ccc;
  margin: 0 5px;
}

.popup-content {
  background-color: #fcfcfc;
  padding: 20px;
  height: 50vh; /* 设置为页面一半的高度 */
  overflow-y: auto; /* 如果内容超出则滚动 */
}

.popup-header {
  font-size: 25px;
  font-weight: bold;
  margin-bottom: 15px;
  text-align: center; /* 居中显示 */
}

.popup-property-row {
  margin-bottom: 30px; /* 增加行之间的间距 */
  padding-bottom: 10px;
}

.popup-property-label {
  font-size: 25px; /* 增大字体 */
  font-weight: bold; /* 加粗字体 */
}

.popup-property-value {
  font-size: 16px;
  color: #333;
}

.divider2 {
  border-bottom: 1px solid #ddd; /* 添加分割线 */
  margin: 0 -20px; /* 确保分割线从边到边 */
}

.shop-info {
	margin-top: 10px;
	width: 100%;
	border-radius: 10px;
    background-color: #008fd7;
    padding: 10px;

    .info-row1 {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .shop-logo {
            width: 60px;
            height: 60px;
            border-radius: 30px;
        }

        .shop-header {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-left: 10px;

            .shop-name {
				width: 50%;
                font-size: 18px;
                font-weight: bold;
            }

            .follow-btn {
				width: 47%;
				
                background-color: #00f300;
                padding: 5px 10px;
                border-radius: 5px;
            }
        }
    }

    .shop-details {
        font-size: 14px;

        .description {
            margin: 5px 10px;
        }

        .info-row2 {
            display: flex;
            justify-content: space-between;
            margin-top: 5px;
			margin-left: 5px;

        }
    }
}
.shop-level {
  display: flex;
  align-items: center;
}
.image_scroll {
 margin-top: 10px;
}

.image_item {
  width: 100%; /* 宽度占满容器 */
  height: auto; /* 高度按比例调整 */
  display: block; /* 防止图片底部出现间隙 */
}
.icon-text-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}

.text {
  margin-left: 5px; /* 图标和文字之间的间距 */
  font-size: 16px; /* 根据需求调整字体大小 */
  color: #000000;
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  display: flex;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
  z-index: 1000;
}

.footer-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #5e5e5e;
  font-size: 14px;
  font-weight: bold; /* 文字加粗 */
}

.footer-item text {
  margin-top: 5px;
}
.introduce{
	margin-top: 10px;
	background-color: #ffffff;
	border-radius: 10px;
}
/* 分享与联系客服 */
.footer-item:nth-child(1),
.footer-item:nth-child(2) {
  flex: 1; /* 占据较小比例 */
}

/* 加入购物车 */
.add-to-cart {
  flex: 2; /* 占据较大比例 */
   background-color: #ff557f;
   color: #ffffff;
   border-radius: 30px;
   font-weight: bold;
}

/* 立即购买 */
.buy-now {
  flex: 2; /* 占据较大比例 */
  background-color: #ff0000;
  color: #ffffff;
  font-weight: bold;
    border-radius: 25px;
}
//购买弹窗
.popup-content {
  background-color: #ffffff;
  border-radius: 16px 16px 0 0;
  padding: 16px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 50PX;
}

.popup-header {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  margin-bottom: 16px;
}

.popup-body {
  flex: 1;
  overflow-y: auto; /* 滚动支持 */
}

.sku-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  border-bottom: 1px solid #f5f5f5;
  padding-bottom: 8px;
}

.sku-name {
  font-size: 20px;
  color: #666666;
  flex: 2; /* 左对齐并占较大空间 */
}

.sku-price {
  font-size: 14px;
  color: #ff4d4f;
  text-align: center;
  flex: 1;
}

.sku-quantity {
  display: flex;
  align-items: center;
}

.decrement-btn, .increment-btn {
  background-color: #00aa00;
  color: #ffffff;
  border: none;
  font-size: 20px;
  width: 40px;
  height: 40px;
  border-radius: 4px;
  text-align: center;
  line-height: 35px;
  cursor: pointer;
}

.quantity-input {
  width: 50px;
  text-align: center;
  margin: 0 8px;
  font-size: 16px;
  color: #333333;
  border: 1px solid #cccccc;
  border-radius: 4px;
  height: 32px;
  padding: 0 4px;
}

.popup-footer {
  display: flex;
  justify-content:space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f5f5f5;
}

.total-amount {
	flex: 5;
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.confirm-btn {
	flex: 2;
  background-color: #00aa00;
  color: #ffffff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.confirm-btn:hover {
  background-color: #e33e3f;
}

</style>
